<template>
    <!-- 
        1.dialog的显示与否是通过 :visible.sync的值来控制的
        2.close-on-click-modal="false"控制点击遮罩是否隐藏弹出层；
    -->
    <el-dialog title="添加子分类" width="560px" :visible.sync="addCategoryDialogVisible" :close-on-click-modal="false">
        <!-- rules表示绑定我们自定义的规则 -->
        <el-form :model="addDept" :rules="rules" ref="addForm">
   

            <el-form-item label="名称" label-width="78px" prop="name">
                <el-input v-model="addDept.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="父分类" label-width="78px" prop="categoryId">
                <el-input v-model="cid" autocomplete="off" :value="this.categoryId" disabled></el-input>
            </el-form-item>
            
            <el-form-item label="排序" label-width="78px" prop="sort">
                <el-input-number v-model="addDept.sort" controls-position="right" @change="handleChange" :min="0" :max="100"></el-input-number>
            </el-form-item>   
            <el-form-item label="是否显示" label-width="78px" prop="online">
                <el-switch
                v-model="addDept.online"
                active-color="#13ce66"
                inactive-color="#ff4949">
            </el-switch>
            </el-form-item>
            <el-form-item label="图片" label-width="78px" prop="img">   
                <el-upload
                    class="avatar-uploader"
                    action=""
                    :show-file-list="false"
                    :http-request="uploadFile"
                    :on-success="handleMainImgSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="this.addDept.img" :src="this.addDept.img" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
        </el-form-item>
        <el-form-item label="描述" label-width="78px" prop="description">
                <el-input v-model="addDept.description" autocomplete="off"></el-input>
            </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="closeAndReset">取 消</el-button>
            <el-button type="primary" @click="sureAdd">确 定</el-button>
        </div>
    </el-dialog>
</template>
<script>
// import axios from 'axios'
import http from '@/utils/request.js'
const OSS = require('ali-oss')
    const client= new OSS({
      accessKeyId: 'LTAI5tBRSqJDJyEqimryPDzH',  // 查看你自己的阿里云KEY
      accessKeySecret: 'wP3KENQ5jPYlwSf0vKooIiFmOH9vT4', // 查看自己的阿里云KEYSECRET
      bucket: 'll0803', // 你的 OSS bucket 名称 
      region: 'oss-cn-hangzhou', // bucket 所在地址，我的是 华北2 北京
      // cname: true // 开启自定义域名上传
      // endpoint:"file.xxxx.live" // 自己的域名
    })
export default {
    data() {
        return {
            value: true,
            num :  0,
            cid:localStorage.getItem('cid'),
            specKeys:[],
            fileList:[],
            
            options :[],
            // addDeptDialogVisible是用来控制弹出框是否显示, false表示不显示；true表示显示
            addCategoryDialogVisible: false,
            addDept: {
                id:'',
                name: '',
                categoryId: '',
                online: '',
                img:'',
                sort:''

          
            },
          
        }
    },
    mounted(){
// categoryId
        console.log("categoryId--->",localStorage.getItem('cid'));
        
    //     console.log("chooseData-------------->>",this.chooseData);

    //     http.get(`/category`).then((res)=>{
    //         this.options = res

    //         console.log("res============>",res);
    //         res.forEach(element => {
               
    //             console.log("elements打印：------>",element,element.name,this.options.label);
    //         });


    //     },
    // )

},
    methods: {
        // 确认添加
        async sureAdd() {
            try {
                // 通过await的方式校验表单的时候，如果校验不通过，this.$refs.editForm.validate()
                // 会抛出异常
                
                // this.addDept.parentId = this.addDept.parentId.reverse()[0]

                console.log("this.addDept.parentId----------->>>",this.addDept.categoryId);
                //await this.$refs.addForm.validate()
                // 代码如果能走下来，表示校验通过
                this.addDept.categoryId = this.cid
                await http.post(`/subCategory`, this.addDept)
                this.fileList = [] 
                // 编辑成功的提示消息
                this.$message({ message: '添加成功', type: 'success', duration: 1000})
                // 隐藏模态框
                this.addCategoryDialogVisible = false
                // 重置表单
                this.$refs.addForm.resetFields()
                // 重新查询数据
                this.$emit('refresh')
            }catch(err) {
                console.log(err);
            }
        },
         //主图方法
      handleMainImgSuccess(file) {
        this.addDept.img = file.url
        // this.fileList = [] 
         console.log(this.addDept.img);
         

      },
      beforeAvatarUpload(file) {
        const isJPEG = file.type === 'image/jpeg'
        const isJPG = file.type === 'image/jpg'
        const isPNG = file.type === 'image/png'
        const imgFormat = !isJPG && !isJPEG && !isPNG
        const isLt4M = file.size / 1024 / 1024 < 4 
        if (imgFormat) {
          this.$message.error('上传头像图片只能是JPG或者PNG格式!');
        }
        if (!isLt4M) {
          this.$message.error('上传头像图片大小不能超过 4MB!');
        }
        return !imgFormat && isLt4M
      },
    async uploadFile (options) {
    try {
        let file = options.file; // 拿到 file
        let fileName = file.name.substr(0,file.name.lastIndexOf('.'))
        let date = new Date().getTime()
        let fileNames = `${date}_${fileName}` // 拼接文件名，保证唯一，这里使用时间戳+原文件名
              // 上传文件,这里是上传到OSS的 uploads文件夹下
        client.put('subCategory/' + fileNames, file).then(res=>{
        if (res.res.statusCode === 200) {
        options.onSuccess(res)
        }else {
            options.onError("上传失败")
        }
      })
        }catch (e) {
         options.onError("上传失败")
        }
      },
      
      
      
        // 关闭并重置
        closeAndReset() {
            // 隐藏模态框
            this.addCategoryDialogVisible = false
            this.fileList = [] 
            // 重置表单
            this.$refs.addForm.resetFields()
        },
        
        
    }
}
</script>

<style>

</style>